package com.blb.bulletscreen;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * 弹幕服务器
 */
public class BulletScreenServer {

    public static final Integer PORT = 8888;

    public void start(){
        System.out.println("启动弹幕服务器");
        //创建接收客户端的线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(4);
        //创建工作线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try {
            //创建启动对象
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            //设置启动参数 1 线程组 2 通道类型 3 连接队列长度 4 初始化器
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //设置管道的编码解码以及自定义处理器
                            ChannelPipeline pipeline = ch.pipeline();
                            //http解码器
                            pipeline.addLast("http-decodec", new HttpRequestDecoder());
                            //http消息聚合器 用于解析post正文的参数
                            pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536));
                            //http编码器
                            pipeline.addLast("http-encodec", new HttpResponseEncoder());
                            //分块传输器
                            pipeline.addLast("http-chunked", new ChunkedWriteHandler());
                            //websocket协议处理器
                            pipeline.addLast("WebSocket-protocol", new WebSocketServerProtocolHandler("/ws"));
                            //自定义弹幕处理器
                            pipeline.addLast("WebSocket-request", new BulletScreenServerHandler());
                        }
                    });
            //绑定本机端口
            ChannelFuture sync = serverBootstrap.bind(PORT).sync();
            //关闭端口
            sync.channel().closeFuture().sync();
        }catch (Exception ex){
            ex.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new BulletScreenServer().start();
    }
}
